#!/usr/bin/env python

"""ConfigDict - a wrapper for a config section to make it act like a dictionary."""

from UserDict import DictMixin
from ConfigParser import NoOptionError

class ConfigDict(DictMixin):

    def __init__(self, config, section):
        if not config.has_section(section):
            raise ValueError("Config object does not have a"
                             " '%s' section." % section)
        self._config = config
        self.section = section

    # Methods for DictMixin
    def __getitem__(self, key):
        try:
            return self._config.get(self.section, key)
        except NoOptionError, msg:
            raise KeyError(msg)

    def __setitem__(self, key, value):
        self.__config.set(self.section, key, value)

    def __delitem__(self, key):
        if not self._config.remove_option(self.section, key):
            raise Keyerror("Tried to remove nonexistent key '%s'." % key)
        
    def keys(self):
        return self._config.options(self.section)


    # We have an analogue for has_key, so use it.
    def has_key(self, key):
        return self._config.has_option(self.section, key)

    # The "get" and "items" methods of some of the configparsers can take
    # "raw" and "vars" arguments. So we offer an extended interface and to
    # these things directly


    # Just pass on all the arguments
    def items(self, *args, **kwargs):
        return self._config.items(self.section, *args, **kwargs)

    # Deal with the value argument, which means we can't use positional arguments
    def get(self, key, value=None, **kwargs):
        if self.has_key(key):
            return self._config.get(self.section, key, **kwargs)
        return value



